package com.ldcc.report_system.ui.report;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;

import com.ldcc.report_system.ApplicationConfig;
import com.ldcc.report_system.ReportApplication;
import com.ldcc.report_system.api.param.DayReportParam;
import com.ldcc.report_system.api.results.DayReportResult;
import com.ldcc.report_system.databinding.ActivityAddDayReportBinding;
import com.ldcc.report_system.listener.SoftKeyBoardListener;
import com.ldcc.report_system.util.ActivitySkipUtil;
import com.ldcc.report_system.util.AlertUtil;
import com.ldcc.report_system.util.KeyBroadUtils;
import com.ldcc.report_system.util.LoadingUtil;
import com.ldcc.report_system.util.ServerDateUtils;
import com.ldcc.report_system.util.WindowUtils;
import com.ldcc.report_system.util.http.ClientRequestManage;
import com.ldcc.report_system.util.http.HttpObserver;
import com.ldcc.report_system.util.http.ServerResponse;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * @author wwj[yeshengkele@outlook.com]
 * @description 添加日报界面
 */
public class AddDayReportActivity extends AppCompatActivity {
    public static final String TAG = "AddDayReportActivity";
    private ActivityAddDayReportBinding addDayReportBinding;

    // 主界面原始高度
    private int addReportHeight;

    // 添加标识
    public static final int ADD_FLAG = 0;
    // 查看标识
    public static final int SHOW_FLAG = 1;
    // 修改标识
    public static final int UPDATE_FLAG = 2;

    // 界面操作标识, 默认添加操作
    private int operationFlag = AddDayReportActivity.ADD_FLAG;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.addDayReportBinding = ActivityAddDayReportBinding.inflate(getLayoutInflater());
        setContentView(this.addDayReportBinding.getRoot());
        // 设置界面顶部为透明
        WindowUtils.setWindowTopTransparent(getWindow());
        this.initPage();
    }

    /***
     * @description 初始化页面
     */
    private void initPage() {
        // 看日志
        this.addDayReportBinding.commitReportBottomBtn.showReportBtn.setOnClickListener(view ->
                ActivitySkipUtil.backMainActivityFragment(this, ApplicationConfig.SHOW_REPORT_FRAGMENT));
        // 写日志
        this.addDayReportBinding.commitReportBottomBtn.addReportBtn.setOnClickListener(view ->
                ActivitySkipUtil.backMainActivityFragment(this, ApplicationConfig.ADD_REPORT_FRAGMENT));
        // 禁用日期选择控件事件
        this.addDayReportBinding.datePickerBtn.setEnabled(false);

        // 判断是否为空，从而确定是查看操作还是添加操作
        String dataId = getIntent().getStringExtra(ActivitySkipUtil.DATA_ID);
        if (dataId != null) {
            this.getDayReport(dataId);
            // 数据id不为空，查看或者编辑操作
            if (getIntent().getBooleanExtra(ActivitySkipUtil.DATA_EDIT_FLAG, false)) {
                // 编辑操作
                this.operationFlag = AddDayReportActivity.UPDATE_FLAG;
                setDayReportEvent();
                // 提交日志
                this.addDayReportBinding.commitReportBottomBtn.commitReportBtn.setOnClickListener(view -> {
                    updateDayReport(dataId);
                });
            } else {
                // 查看操作
                this.operationFlag = AddDayReportActivity.SHOW_FLAG;
                setActivityEnable(false);
                // 设置提交按钮
                addDayReportBinding.commitReportBottomBtn.commitReportLayout.setVisibility(View.GONE);
            }

        } else {
            // 数据id为空，添加操作
            this.operationFlag = AddDayReportActivity.ADD_FLAG;
            setDayReportEvent();
            // 提交日志
            this.addDayReportBinding.commitReportBottomBtn.commitReportBtn.setOnClickListener(view -> {
                addDayReport();
            });
        }

    }

    /**
     * @param dayReportId 日报id
     * @description 查看操作执行的事情
     */
    private void getDayReport(String dayReportId) {
        ClientRequestManage.getInstance().getDayReportApi().getById(dayReportId).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<DayReportResult>(ReportApplication.getContext(), null) {
                    @Override
                    public void onSuccess(ServerResponse<DayReportResult> response_entity) {
                        DayReportResult data = response_entity.getData();
                        String gmtCreate = data.getGmtCreate();
                        // 设置日期
                        addDayReportBinding.datePickerBtn.setDate(
                                ServerDateUtils.getDateYear(gmtCreate),
                                ServerDateUtils.getDateMonth(gmtCreate),
                                ServerDateUtils.getDateDay(gmtCreate)
                        );
                        //  设置值
                        addDayReportBinding.finish.getEditValue().setText(data.getFinish());
                        addDayReportBinding.tomorrowPlan.getEditValue().setText(data.getTomorrowPlan());
                        addDayReportBinding.beContinued.getEditValue().setText(data.getBeContinued());
                        addDayReportBinding.remarks.getEditValue().setText(data.getRemarks());
                    }
                });
    }

    /**
     * @description 禁用界面上所有输入组件
     */
    private void setActivityEnable(boolean enable) {
        addDayReportBinding.finish.getEditValue().setEnabled(enable);
        addDayReportBinding.tomorrowPlan.getEditValue().setEnabled(enable);
        addDayReportBinding.beContinued.getEditValue().setEnabled(enable);
        addDayReportBinding.remarks.getEditValue().setEnabled(enable);
    }


    /**
     * @description 添加日报需要执行的事情
     */
    private void setDayReportEvent() {
        // 监听键盘事件
        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height, int visibleHeight) {
                //  这里才会有高度
                addReportHeight = addDayReportBinding.addReportMainView.getHeight();
                Log.e(TAG, "keyBoardShow: 获取当前高度：" + addReportHeight);
                addDayReportBinding.addReportMainView.setLayoutParams(
                        new LinearLayout.LayoutParams(addDayReportBinding.addReportMainView.getWidth(), addReportHeight - height));
            }

            @Override
            public void keyBoardHide(int height, int visibleHeight) {
                addDayReportBinding.addReportMainView.setLayoutParams(
                        new LinearLayout.LayoutParams(addDayReportBinding.addReportMainView.getWidth(), addReportHeight));
            }
        });
    }


    /**
     * @description 添加日报
     */
    private void addDayReport() {
        // 完成的工作
        String finish = this.addDayReportBinding.finish.getEditValue().getText().toString();
        // 未完成
        String beContinued = this.addDayReportBinding.beContinued.getEditValue().getText().toString();
        // 明日计划
        String tomorrowPlan = this.addDayReportBinding.tomorrowPlan.getEditValue().getText().toString();
        // 备注信息
        String remarks = this.addDayReportBinding.remarks.getEditValue().getText().toString();
        ClientRequestManage.getInstance().getDayReportApi().save(new DayReportParam() {{
            setFinish(finish);
            setBeContinued(beContinued);
            setTomorrowPlan(tomorrowPlan);
            setRemarks(remarks);
        }}).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<Object>(ReportApplication.getContext(), LoadingUtil.dialogLoadingOpen("请稍后", "正在连接服务器....", this)) {
                    @Override
                    public void onSuccess(ServerResponse<Object> response_entity) {
                        // 不带参数跳转页面
                        ActivitySkipUtil.backMainActivityFragment(AddDayReportActivity.this, ApplicationConfig.SHOW_REPORT_FRAGMENT);
                    }
                });
    }

    /**
     * @description 修改日报
     */
    private void updateDayReport(String id) {
        // 完成的工作
        String finish = this.addDayReportBinding.finish.getEditValue().getText().toString();
        // 未完成
        String beContinued = this.addDayReportBinding.beContinued.getEditValue().getText().toString();
        // 明日计划
        String tomorrowPlan = this.addDayReportBinding.tomorrowPlan.getEditValue().getText().toString();
        // 备注信息
        String remarks = this.addDayReportBinding.remarks.getEditValue().getText().toString();

        ClientRequestManage.getInstance().getDayReportApi().update(new DayReportParam() {{
            setId(id);
            setFinish(finish);
            setBeContinued(beContinued);
            setTomorrowPlan(tomorrowPlan);
            setRemarks(remarks);
        }}).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<Object>(ReportApplication.getContext(), null) {

                    @Override
                    public void onSuccess(ServerResponse<Object> response_entity) {
                        AlertUtil.shortTime("修改成功");
                        KeyBroadUtils.hideKeyboard(ReportApplication.getContext(), getWindow().getDecorView().getWindowToken());
                    }
                });
    }


    /**
     * @description 返回键事件, 返回, 选择日报界面
     */
    @Override
    public void onBackPressed() {
        if (isAdd()) {
            ActivitySkipUtil.backMainActivityFragment(this, ApplicationConfig.ADD_REPORT_FRAGMENT);
        } else {
            ActivitySkipUtil.backMainActivityFragment(this, ApplicationConfig.SHOW_REPORT_FRAGMENT);
        }

    }


    /**
     * @return 是否为添加操作
     */
    public boolean isAdd() {
        return this.operationFlag == AddDayReportActivity.ADD_FLAG;
    }

    /**
     * @return 是否为修改操作
     */
    public boolean isUpdate() {
        return this.operationFlag == AddDayReportActivity.UPDATE_FLAG;
    }

    /**
     * @return 是否为查看操作
     */
    public boolean isShow() {
        return this.operationFlag == AddDayReportActivity.SHOW_FLAG;
    }


}